package com.xh.demo.controller;

import com.xh.demo.common.annotation.MyRequestBody;
import com.xh.demo.common.enums.ErrorEnum;
import com.xh.demo.common.exception.BusinessException;
import com.xh.demo.domain.po.User;
import com.xh.demo.domain.vo.AJAXResult;
import com.xh.demo.domain.vo.UserVo;
import com.xh.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @Name TestController
 * @Description
 * @Author wen
 * @Date 2019-07-31
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IUserService userService;

    @GetMapping("/date")
    @ResponseBody
    public String testDate(@RequestParam("date") Date date){
        return "success" + date.getTime();
    }

    @PostMapping("/user")
    @ResponseBody
    public String testUser(@MyRequestBody UserVo userVo){
        return "success:" + userVo;
    }

    @GetMapping("/index")
    @ResponseBody
    public String index(){
        return "hellow spring annotation dev!";
    }

    @GetMapping("/user/{id}")
    @ResponseBody
    public User user(@PathVariable("id") int id){
        return userService.getById(id);
    }

    @GetMapping("/ex")
    @ResponseBody
    public String exception(){
        int i = 0 / 0;
        return "hellow spring annotation dev!";
    }

    @GetMapping("/bex")
    @ResponseBody
    public AJAXResult businessException(){
        if(1 == 1){
            throw new BusinessException(ErrorEnum.FAIL);
        }
        return AJAXResult.fail();
    }

    @GetMapping("/upload")
    public String upload(){
        return "file_upload";
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file){
        try {
            String path = "E:/" + file.getOriginalFilename();
            file.transferTo(new File(path));
        } catch (IOException e) {
            throw new BusinessException(ErrorEnum.FILE_WRITE_ERROR);
        }
        return "success";
    }

}
